<?php
class IndexAction extends CommonAction {
	public $memberInfo=array();
	public function _initialize(){

		parent::_initialize();
		Vendor('Weixin.Weixin');
		$d['token']=getSysVal('token');
        $d['appid']=getSysVal('appid');
        $d['appsecret']=getSysVal('appsecret');
        $this->weixin=new WeixinChat($d);
		//echo __SITEID__;
		
		//F('xxxxxxxxxxxxxxxxx',$_GET);
		
        $this->weixin->valid();
		//exit;
        $revdata=$this->weixin->getRev()->getRevData();
		$this->revdata=$revdata;
		$this->assign('openid',$revdata['FromUserName']);
		//$this->weixin->text('关键词不能识别')->reply(); 
		
		$data['openid'] = $revdata['FromUserName'];
		$data['site_id'] = __RELATEID__;
		//if($revdata['EventKey'] != '')
        ////////
        
        ////////
		$memberDB = D('Member');
		$member = $memberDB -> where($data) -> find();
		$pwd = rand(100000, 999999);
        $data['password'] = md5($pwd);
		$this -> memberInfo = $member;
		if(!$member){
			$member['id'] = $memberDB -> data($data) -> add();
			F('member_idxxx', $member['id']);
			
			$this->memberInfo = $data;
		}
		
		$this->memberInfo = $login_result = $this->weixin->getUserInfo($revdata['FromUserName']);
		$this->memberInfo['id'] = $member['id'];
		$login_result['id'] = $member['id'];
		$memberDB -> savewx($login_result);
        $memberDB -> addUser($member['id']);
		//信息类型
		
		
		if(($revdata['MsgType'] == 'text' && $revdata['Content'] == 'qrcode') || ($revdata['MsgType'] == 'event' && $revdata['EventKey'] == 'qrcode')){
			 //echo '';
			 //做一个缓存排重
			 if(!S('qrMsgId'.$revdata['FromUserName'].$revdata['FromUserName'].$revdata['CreateTime'])){
				 S('qrMsgId'.$revdata['FromUserName'].$revdata['FromUserName'].$revdata['CreateTime'],$revdata['FromUserName'].$revdata['CreateTime'],20);
			    // S('qrMsgId'.$revdata['MsgId'],$revdata['MsgId'],20);
			     @curlRequest(U('Home/Ajax/createaffqr', array('id' => $this->memberInfo['id']), true, false, true));
			     $this->weixin->text('生成成功！')->reply();
			 }
			 exit;
		}
		
		
		
		if(strpos($revdata['EventKey'],'bind_') !== false){
			$memberId = explode('bind_',$revdata['EventKey']);
			$where['openid']=$revdata['FromUserName'];
			$where['site_id']=['gt',13];
			if(!$memberDB->where($where)->find()){
				$where['id']=$memberId[1];
				$where['site_id']=$memberId[2];
				$ret=$memberDB->save($where);
			}
		}
		
		
		switch($revdata['MsgType']){
			case 'text' : $this->re_keyword($revdata['Content'],$revdata['FromUserName']); break;
			case 'image' : $this->re_news(); break;
			case 'event' : $this->re_event($revdata); break;
		}
	}
	
	//事件回复
	private function re_event($revdata){
		
		//绑定数据到数据库
		if($revdata['Event'] == 'subscribe'){
			
			
			if(F('subscribe_returnUrl'.$revdata['FromUserName'])){
				$returnText = F('subscribe_returnUrl'.$revdata['FromUserName']);
				F('subscribe_returnUrl'.$revdata['FromUserName'],'');
				sendWXMsg($revdata['FromUserName'], $returnText);
			}
			
			$this -> updatePid($revdata);
			
			
			//关注营销
			$Subscribelist = M('Subscribe') -> where(array('status' => 1, 'site_id' => __SITEID__)) -> select();
			foreach($Subscribelist as $k => $v){
				import("@.ORG.Subscribe.".$v['classname']);
				$class = $v['classname'];
				$Threelevel = new $class(__SITEID__, $this -> memberInfo['id']); 
				$Threelevel -> init();
			}
			// 关注类优惠券发放			
			import("@.ORG.Coupon.Coupon");
			$Coupon = new Coupon();
			$Coupon->sendSubscribeCoupon($revdata['FromUserName']);
			
			
			$memberDB = D('Member');
		    $member = $memberDB -> where(array('openid' => $revdata['FromUserName'])) -> data(array('is_subscribe' => 1, 'reg_time' => time())) -> save();
			M('Member_member') -> where(array('smember_id' => $this->memberInfo['id'])) -> data(array('is_subscribe' => 1)) -> save();
			
			
			$loginid = str_replace('qrscene_','',$revdata['EventKey']);
			$memberdb = M('Member');
			$siteid = MCS(md5($loginid));
			$uret = $memberdb -> where(array('site_id' => $siteid,'loginid' => md5($loginid))) -> find();
			if(!is_array($uret)  && $siteid > 0){
				$memberDB = D('Member');
				//
				
				//
				//不是主站点登录时写入从站点的会员数据
				if($siteid != __SITEID__){
					$data['openid'] = $revdata['FromUserName'];
					$data['site_id'] = $siteid;
					
					$member = $memberDB -> where($data) -> find();
					$this -> memberInfo = $member;
					if(!$member){
						$pwd = rand(100000, 999999);
						$data['password'] = md5($pwd);
						$member['id'] = $memberDB -> data($data) -> add(); 
						$this->memberInfo = $data;
						//sendWXMsg($revdata['FromUserName'], '您正在注册【'.$sitename.'】的用户，系统为您分配的用户名是：weixin'.$member['id'].'，初始化密码为：'.$pwd);
					}
					$this->memberInfo = $login_result = $this->weixin->getUserInfo($revdata['FromUserName']);
					$this->memberInfo['id'] = $member['id'];
					$login_result['id'] = $member['id'];
					$memberDB -> savewx($login_result);
				}
				$sitename = M('Site') -> where(array('id' => $siteid)) -> getField('title');
				$memberdb -> where(array('site_id' => $siteid,'openid' => $revdata['FromUserName'])) -> data(array('loginid' => md5($loginid))) ->save();
				sendWXMsg($revdata['FromUserName'], '您正在登录【'.$sitename.'】');
				
				
			}
			
		}
		//更新关注状态
		if($revdata['Event'] == 'unsubscribe'){ 
			$memberDB = D('Member');
		    $member = $memberDB -> where(array('openid' => $revdata['FromUserName'])) -> data(array('is_subscribe' => 0)) -> save();
			M('Member_member') -> where(array('smember_id' => $this->memberInfo['id'])) -> data(array('is_subscribe' => 0)) -> save();
		}
		
		
		
			switch($revdata['Event']){
					case 'CLICK' : $this->re_keyword($revdata['EventKey']);break; 
					case 'subscribe' :$this->re_keyword('首页', $revdata['FromUserName']); break;
					case 'SCAN' : $this->re_scan($revdata); break;
				}
		
	} 
	
	private function updatePid($revdata){
		
		if(strpos($revdata['EventKey'],'qrscene_aff_') === false){
			$memberDB = D('Member');
			$member = $memberDB -> where(array('openid' => $revdata['FromUserName'])) -> find();
			$userlist = $memberDB -> getUserArr($member['pid']);
				//F('userlist', $userlist);
				//发送通知
				/*foreach($userlist as $k => $v){
					$news[0]['title'] = '会员加入通知';
					$news[0]['description'] = 'V'.($v['deep']).'客户加入:'. $member['nickname']."\r\n加入时间：".date('Y-m-d H:i:s');
					$news[0]['url'] = U('Member/Index/userlist',array(),true,false,true);
					$this -> weixin -> sendCustomMessage($v['openid'], $news, 'news');
				}*/
		    return false;
		}
		
		//扫描和关注两个事件的key前缀不同，用aff_来分割字符得到第二个值即为推荐ID
		
		if(strpos($revdata['EventKey'],'aff_') !== false){
			$parent = explode('aff_',$revdata['EventKey']);
		}
		F('ws', $parent);
		$parent_id = intval($parent[1]);
		//F('ws', $revdata['EventKey']);
		if($parent_id > 0 && strpos($revdata['EventKey'],'aff_') !== false){
			$memberDB = D('Member');
			$member = $memberDB -> where(array('openid' => $revdata['FromUserName'])) -> find();
			F('ws', $member);
			/*$ret = $memberDB -> updatePid($member['id'], $parent_id);
			
			if($ret){
				//查询上家OPENID
				//$parent_openid = $memberDB -> where(array('id' => $parent_id)) -> getField('id');
				$userlist = $memberDB -> getUserArr($parent_id);
				//F('userlist', $userlist);
				//发送通知
				
				foreach($userlist as $k => $v){
					$news[0]['title'] = '会员加入通知';
					$news[0]['description'] = 'V'.($v['deep']).'客户加入:'. $member['nickname']."\r\n加入时间：".date('Y-m-d H:i:s');
					$news[0]['url'] = U('Member/Index/userlist',array(),true,false,true);
					$this -> weixin -> sendCustomMessage($v['openid'], $news, 'news');
				}
			} */
			
			return true;
	    }
		return false;
	}
	
	private function re_scan($revdata){
		if($this -> updatePid($revdata)){
			exit;
		}
		$loginid = str_replace('qrscene_','',$revdata['EventKey']);
		$memberdb = M('Member');
		
		$siteid = MCS(md5($loginid));
		
		$uret = $memberdb -> where(array('site_id' => $siteid,'loginid' => md5($loginid))) -> find();
		if(!is_array($uret) && $siteid > 0){
			
			
			$memberDB = D('Member');
				//
				
				//
				//不是主站点登录时写入从站点的会员数据
				if($siteid != __SITEID__){
					
					$data['openid'] = $revdata['FromUserName'];
					$data['site_id'] = $siteid;
					
					$member = $memberDB -> where($data) -> find();
					$this -> memberInfo = $member;
					if(!$member){
						$pwd = rand(100000, 999999);
						$data['password'] = md5($pwd);
						$member['id'] = $memberDB -> data($data) -> add(); 
						$this->memberInfo = $data;
						//sendWXMsg($revdata['FromUserName'], '您正在注册【'.$sitename.'】的用户，系统为您分配的用户名是：weixin'.$member['id'].'，初始化密码为：'.$pwd);
					}
					$this->memberInfo = $login_result = $this->weixin->getUserInfo($revdata['FromUserName']);
					//F('ws', $this->memberInfo);
					$this->memberInfo['id'] = $member['id'];
					$login_result['id'] = $member['id'];
					$memberDB -> savewx($login_result);
					
				}
			
			$sitename = M('Site') -> where(array('id' => $siteid)) -> getField('title');
		    $memberdb -> where(array('site_id' => $siteid,'openid' => $revdata['FromUserName'])) -> data(array('loginid' => md5($loginid))) ->save();
			$this->weixin->text('您正在登录【'.$sitename.'】')->reply();
		}else{
			exit;
		}
		
	} 
	//回复图文
	private function re_news(){
		exit();
	}
	
	//根据关键词回复
	public function re_keyword($key,$openid=''){
		
		
		//客服转接
		if($key == 'kefu'){
			$this->weixin -> transferCustomerService();
		}
		
		
		$reply=M('Reply')->where("keyword='{$key}' and site_id=".__SITEID__)->find();
		
		if(!is_array($reply) && $key != '_任意_'){
			
			$this->re_keyword('_任意_');
		}
		if($reply['content'] == '' && $key == '_任意_'){
			if(getSysVal('pigcmsinterface') != ''){
				$this->pigcmsInterface(getSysVal('pigcmsinterface'));
				
			}exit;
		}
		if($reply['MsgType'] == 'text'){
			$reply['content'] = str_replace('@nickname@', $this->memberInfo['nickname'], $reply['content']);
		}
		
		switch($reply['MsgType']){
			case 'text' :$this->weixin->text($reply['content'])->reply(); break;
			case 'news' :$this->re_newsForKeyword($reply['content']);break;
			case 'image' :$this->re_image($reply['img_url']);break;
			case 'vc' :$this->vcard($reply['content']);break;
			default : $this->weixin->text('关键词不能识别')->reply(); break;
		}
	}
	
	//关键词回复图文
	private function re_image($image){
		$this->weixin->image('./Public'.$image)->reply();
	}
	
	//关键词回复图文
	private function re_newsForKeyword($reply){
		$data = unserialize($reply);
		$re_data=array();
		foreach($data as $k=>$v){
			$re_data[$k]['title']=$v['title'];
			$re_data[$k]['description']= $v['description'];
			$re_data[$k]['picUrl']='http://'.$_SERVER['SERVER_NAME'].'/Public/'.$v['img_url'];
			if(!(substr($v['link'],0,7) == 'http://' || substr($v['link'],0,8) == 'https://')){
				$v['link'] = 'http://'.$_SERVER['SERVER_NAME'].$this->fetch('',$v['link']).'?openid='.$this->revdata['FromUserName'];
			}else{
				$v['link'] = $v['link'].'?openid='.$this->revdata['FromUserName'];
			}
			$re_data[$k]['url'] = $v['link'];
		}
		$this->weixin->news($re_data)->reply();
	}
	
	
 	//对接小猪CMS回复接口
	public function pigcmsInterface($url){
	    $ret = curlRequest($url, $GLOBALS["HTTP_RAW_POST_DATA"]);
		F('asdfasdfasdfasdfasdf',$ret);
		exit($ret);
	}
	
}
 